<template>
  <div>
    <dl class="m-categroy">
      <dt>按拼音首字母选择:</dt>
      <dd
        v-for="item in list"
        :key="item">
        <a :href="'#city-'+item">{{ item }}</a>
      </dd>
    </dl>
    <dl
      v-for="item in block"
      :key="item.title"
      class="m-categroy-section">
      <dt :id="'city-'+item.title">{{ item.title }}</dt>
      <dd>
        <span
          v-for="c in item.city"
          :key="c">
          {{ c }}
        </span>
      </dd>
    </dl>
  </div>
</template>

<script>
import pyjs from 'js-pinyin'

export default {
  name: 'Category',
  props: {
    cities: {
      type: Array,
      require: true,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      list: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
    }
  },
  computed: {
    block() {
      if (!this.cities.length) return
      let p,
        c,
        d = {},
        arr = []
      this.cities.forEach(item => {
        p = pyjs
          .getFullChars(item.name)
          .toUpperCase()
          .slice(0, 1)
        c = p.charCodeAt(0)
        if (c > 64 && c < 91) {
          if (!d[p]) {
            d[p] = []
          }
          d[p].push(item.name)
        }
      })
      for (let [k, v] of Object.entries(d)) {
        arr.push({
          title: k,
          city: v
        })
      }
      arr.sort((a, b) => a.title.charCodeAt(0) - b.title.charCodeAt(0))
      return arr
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/css/changeCity/categroy.scss';
</style>
